import { getWorkflowTemplateNodesById, getActivitiNodeAttrs } from '@/api/spw/workflow.js'
import { reapplyTicket } from '@/api/spw/ticketApply.js'
import { cloneDeep } from 'lodash'

export default {
  async onLoad(options) {
    console.log('options', options)
    this.procDefId = options.procDefId
    this.templateId = options.templateId
    this.formData.workTypeFlag = options.workTypeFlag

    await this.getActivitiInfo(options)

    // 监听ticketDataTicketFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('ticketDataTicketFromOpenerPage', ({ rowData, template, reapply }) => {
      console.log('row-data', rowData)
      console.log('template', template)
      console.log('reapply', reapply)

      this.template = template
      this.ticketData = rowData
      this.reapply = reapply || false
      this.ticketWorkLevel = rowData.ticketWorkLevel
      if (rowData.ticketInfo && Object.keys(rowData.ticketInfo).length) {
        const ticketInfo = rowData.ticketInfo
        this.ticketFormData = Object.assign({}, ticketInfo)
        Object.keys(this.formData).forEach((item) => {
          this.formData[item] = ticketInfo[item] ?? this.formData[item]
        })
        // 再次填写用缓存里面的
        this.ticketWorkLevel = ticketInfo.workLevel
        this.nodeAttrs = cloneDeep(ticketInfo.nodeAttrs)
      } else {
        Object.keys(this.formData).forEach((item) => {
          if (item === 'riskIdentificationArr') {
            this.formData['riskIdentificationArr'] = JSON.parse(rowData.riskIdentification) || []
          }
          this.formData[item] = rowData[item] ?? this.formData[item]
          this.ticketFormData = {
            workLocation: rowData.operationPoint, // 作业地点
            workLevel: rowData.ticketWorkLevel || '', // 作业级别
            workLevelLabel: rowData.ticketWorkLevelLabel || '', // 作业级别
            principal: rowData.directorId || '', // 作业负责人
            unitId: rowData.unitId || '',
            principalLabel: rowData.directorName || '',
            workId: rowData.workId,
            workTypeFlag: rowData.workTypeFlag,
            workTypeLabel: rowData.workTypeLabel
          }
        })
      }

      this.formData.workTypeFlag = rowData.workTypeFlag
      this.formData.specialWorkTypeLabel = rowData.workTypeLabel
    })

    eventChannel.on('addNewTicket', ({ workTypeFlag, workTypeLabel, procDefId }) => {
      this.formData.workTypeFlag = workTypeFlag
      this.formData.specialWorkTypeLabel = workTypeLabel
      this.procDefId = procDefId
    })

    console.log('this.nodeAttrs', this.nodeAttrs)
  },
  computed: {},
  data() {
    return {
      reapply: false,
      template: {},
      ticketData: {},
      nodeAttrs: [],
      procDefId: '',
      templateId: '',
      ticketWorkLevel: ''
    }
  },
  methods: {
    async getActivitiInfo(template) {
      const personAttrs = {}
      const [userRes, nodeRes] = await Promise.all([
        getWorkflowTemplateNodesById(template.templateId),
        getActivitiNodeAttrs(template.procDefId)
      ])
      userRes.data.forEach((item) => {
        personAttrs[item.nodeId] = item
      })
      if (Object.keys(personAttrs).length !== nodeRes.data.length) {
        this.workflowError()
        return
      }
      nodeRes.data.map((item) => {
        item.personData = personAttrs[item.nodeId]
        // 用户组，默认把人全部显示出来
        if (item.personData.reviewerElectType === 'USER_GROUP') {
          item.personData.users.map((item) => {
            item.userId = item.staffId
            item.name = item.staffName
            return item
          })
          item.staffs = JSON.parse(JSON.stringify(item.personData.users))
        } else {
          item.staffs = []
        }
        return item
      })
      this.nodeAttrs = nodeRes.data
    },
    workflowError() {
      uni.showModal({
        title: '提示',
        content: `当前流程节点人员未配置完整，请先在网页端配置流程节点人员`,
        showCancel: false,
        confirmText: '我知道了',
        success: (res) => {
          if (res.confirm) {
            uni.navigateBack()
          }
        }
      })
    },
    /**
     * @description  签名成功
     */
    async onSignatureSuccess(tempFilePath) {
      await reapplyTicket(this.ticketData.ticketId, {
        coordinatorId: this.ticketData.coordinatorId,
        endTime: this.reapplyData.endTime,
        procDefId: this.reapplyData.procDefId,
        staffs: this.reapplyData.staffs,
        startTime: this.reapplyData.startTime,
        ticketContent: JSON.stringify(this.reapplyData),
        ticketWorkLevel: this.reapplyData.workLevel,
        ticketWorkLevelKey: this.reapplyData.ticketWorkLevelKey,
        workId: this.ticketData.workId,
        workType: this.ticketData.workType,
        applicantSignatures: [tempFilePath]
      })
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.emit('ticket:form:success')
      uni.navigateBack()
    }
  }
}
